<template>
    <div class="Carousel">
        <!-- 添加 -->
        <el-row :gutter="20" class="Carousel-Info">
            <el-col :xs="6" :sm="4" :md="3" :lg="2" :xl="2">
                <el-button type="primary" @click="addVisible = true">新增管理员账号</el-button>
            </el-col>
        </el-row>
        <!-- 查询列表 -->
        <el-row class="Carousel-list">
            <el-col :span="24">
                <el-table
                    :data="tableData"
                    border
                    style="width: 100%">
                    <el-table-column
                    prop="id"
                    label="管理员ID"
                    width="200">
                    </el-table-column>
                    <el-table-column
                    prop="username"
                    label="登录名"
                    width="120">
                    </el-table-column>
                    <el-table-column
                    prop="address"
                    label="操作">
                        <template slot-scope="scope" v-if="scope.row.username != 'admin'">
                            <el-popconfirm 
                            confirm-button-text='确认' 
                            cancel-button-text='取消' 
                            icon="el-icon-info" 
                            icon-color="red" 
                            title="确定删除吗？"
                            @confirm="deleteAccount(scope.row.id)"
                            >
                                <!-- <el-button type="text" slot="reference">禁用</el-button> -->
                                <el-button type="danger" size="mini"  slot="reference">删除</el-button>
                                <!-- <el-button type="text" slot="reference">分配权限</el-button> -->
                            </el-popconfirm>
                            &nbsp;
                            <!-- <el-popconfirm 
                            confirm-button-text='确认' 
                            cancel-button-text='取消' 
                            icon="el-icon-info" 
                            icon-color="red" 
                            title="确定删除吗？"
                            @click="updateRole(scope.row.id)"
                            > -->
                                <el-button type="primary" size="mini" slot="reference" 
                                @click="allocation(scope.row)">分配权限</el-button>
                            <!-- </el-popconfirm> -->
                        </template>
                    </el-table-column>
                </el-table>
            </el-col>
        </el-row>
        <div class="block">
              <el-pagination
                  layout="prev, pager, next"
                  :total="pageHelp.total * 10"
                  @current-change="changeCurrentPage"
                  >
              </el-pagination>
          </div>

        <!-- 新增管理员账号 -->
        <el-dialog
        title="新增账号"
        :visible.sync="addVisible"
        width="30%"
        :before-close="handleAddClose">
            <el-form label-width="100px">
                <el-form-item label="账号登录名">
                    <el-input v-model="accountRole.account.username" placeholder="请输入内容" minlength="10"></el-input>
                </el-form-item>
                <el-form-item label="账号密码">
                    <el-input v-model="accountRole.account.password" placeholder="请输入内容"></el-input>
                </el-form-item>
                <el-form-item label="用户角色">
                    <el-select v-model="accountRole.roleId" multiple  placeholder="请选择角色">
                        <el-option
                        v-for="role in roleOptions"
                        :key="role.id"
                        :label="role.roleName"
                        :value="role.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisible = false">取 消</el-button>
                <el-button type="primary" @click="addAcount()">确 定</el-button>
            </span>
        </el-dialog>

        <!-- 分配权限 -->
        <el-dialog
        title="分配权限"
        :visible.sync="addVisibleTwo"
        width="30%"
        :before-close="handleAddCloseTwo">
            <el-form label-width="100px">
                <el-form-item label="账号登录名">
                    <el-input :disabled="true" v-model="updateRole.username" minlength="10"></el-input>
                </el-form-item>
                <el-form-item label="用户角色">
                    <el-select v-model="accountRole.roleId" multiple  placeholder="请选择角色">
                        <el-option
                        v-for="role in roleOptions"
                        :key="role.id"
                        :label="role.roleName"
                        :value="role.id">
                        </el-option>
                    </el-select>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="addVisibleTwo = false">取 消</el-button>
                <el-button type="primary" @click="updateRoleList()">确 定</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
import axios from "axios"
let path = "http://localhost/backstage/account"
export default {
    data(){
        return {
            tableData:[],
            account:{},
            visible: false,
            updateVisible: false,
            addVisible:false,
            addVisibleTwo:false,
            accountRole: {
                account:{
                    username:'',
                    password:'',
                    creationBy: JSON.parse(localStorage.getItem("account")).id
                },
                roleId:'',
                creationBy: JSON.parse(localStorage.getItem("account")).id
            },
            roleOptions:[],
            pageHelp:{
                currentPage : 1,
                perPageSize : 10,
                total:1,
            },
            updateRole:{
                id:'',
                username:'',
            }
            
        }
    },
    methods:{
        handleUpdateClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => {
                  done();
                })
                .catch(_ => {});
        },
        handleAddClose(done) {
            this.$confirm('确认关闭？')
                .then(_ => {
                  done();
                })
                .catch(_ => {});
        },
        handleAddCloseTwo(done) {
            this.$confirm('确认关闭？')
                .then(_ => {
                  done();
                })
                .catch(_ => {});
        },
        warningMessage(info) {
            this.$message({
                message: info,
                type: 'warning'//success、warning
            });
        },
        successMessage(info) {
            this.$message({
                message: info,
                type: 'success'//success、warning
            });
        },
        errorMessage(info) {
            this.$message.error(info);
        },
        addVisibleTF(string){
            this.addVisible = string;
        },

        //点击分配权限按钮
        allocation(row){
            this.updateRole.username=row.username;
            this.updateRole.id=row.id;
            this.selectUserRole();
        },

        //查询用户所具有的的角色
        selectUserRole(){

            axios({
                methods:'get',
                url:"http://localhost/company/user/list",
                params:{
                    accountId:this.updateRole.id,
                },
                headers:{
                    id: JSON.parse(localStorage.getItem("account")).id,
                    token: JSON.parse(localStorage.getItem("account")).token,
                }
            }).then(res => {
                if(res.data.code === 500){
                    this.warningMessage("您未有权限!");
                }else if(res.data.code === 40100){
                    this.addVisibleTwo=true;
                    var arr = res.data.data;
                    var string = '';
                    //循环获取
                    arr.forEach((item,index) =>{
                        string+=item.id+",";
                    })
                    string = string.substring(0, string.length - 1);
                    this.accountRole.roleId = string.split(',').map(String);
                }
            }).catch(error => {
                console.log(error);
            })

        },


        //更新账号权限
        updateRoleList(){
            var role = "";
            if(this.accountRole.roleId!=""){
                this.accountRole.roleId.forEach(element => {
                    role+=element+",";
                });
                role = role.substring(0, role.length - 1);
            };
            axios({
                methods:'get',
                url:"http://localhost/company/user/new",
                params:{
                    accountId:this.updateRole.id,
                    roleId:role,
                    creationBy:JSON.parse(localStorage.getItem("account")).id,
                },
                headers:{
                    id: JSON.parse(localStorage.getItem("account")).id,
                    token: JSON.parse(localStorage.getItem("account")).token,
                }
            }).then(res => {
                if(res.data.code === 500){
                    this.warningMessage("您未有权限!");
                }else if(res.data.code === 30100){
                    this.addVisibleTwo = false;
                    this.successMessage("更改权限成功！")
                    // this.addVisibleTF(false);
                    console.log(res);
                }else if(res.data.code === 30200){
                    this.errorMessage("更改权限失败！")
                    console.log(res);
                }
            }).catch(error => {
                this.errorMessage("查询错误！")
                console.log(error);
            })

        },
        
        //分页查询
        changeCurrentPage(currentPage) {
            console.log(this.pageHelp.currentPage);
            this.pageHelp.currentPage = currentPage;
            axios({
                method: 'get',
                url:path + "/list",
                params: {
                    currentPage: this.pageHelp.currentPage,
                    perPageSize: this.pageHelp.perPageSize,
                },
                headers: {
                    id: JSON.parse(localStorage.getItem("account")).id,
                    token: JSON.parse(localStorage.getItem("account")).token,
                },

            }).then(res => {
                if (res.data.code === 500) {
                    this.warningMessage("您的权限不足！")
                } else if (res.data.code === 40100) {
                    console.log(res.data.data);
                    this.tableData = res.data.data.list;
                    this.pageHelp.total = res.data.data.pages;
                } else {
                    this.errorMessage("查询失败！");
                }

                console.log(res);
            }).catch(error => {
                console.log(error);
            })
        },

        //展示所有管理员账号
        list() {
            axios({
                methods:'GET',
                url:path + "/list",
                params: {
                    currentPage: this.pageHelp.currentPage,
                    perPageSize: this.pageHelp.perPageSize,
                },
                headers:{
                    id: JSON.parse(localStorage.getItem("account")).id,
                    token: JSON.parse(localStorage.getItem("account")).token,
                }
            }).then(res => {
                if (res.data.code === 500) {
                    this.warningMessage("您的权限不足！")
                } else if (res.data.code === 40100) {
                    console.log(res.data.data);
                    this.tableData = res.data.data.list;
                    this.pageHelp.total = res.data.data.pages;
                } else {
                    this.errorMessage("查询失败！");
                }

                console.log(res);
            }).catch(error => {
                console.log(error);
            })
        },

        //新增管理员
        addAcount() {
            var role = "";
            if(this.accountRole.roleId!=""){
                this.accountRole.roleId.forEach(element => {
                    role+=element+",";
                });
                role = role.substring(0, role.length - 1);
            }
            axios({
                methods:'get',
                url:"http://localhost/account/role/user/account",
                params:{
                    username:this.accountRole.account.username,
                    password:this.accountRole.account.password,
                    roleId:role,
                    creationBy:JSON.parse(localStorage.getItem("account")).id,
                },
                headers:{
                    id: JSON.parse(localStorage.getItem("account")).id,
                    token: JSON.parse(localStorage.getItem("account")).token,
                }
            }).then(res => {
                if(res.data.code === 500){
                    this.warningMessage("您未有权限!");
                }else if(res.data.code === 10100){
                    this.successMessage("新增成功！")
                    this.addVisibleTF(false);
                    console.log(res);
                }else if(res.data.code === 40100){
                    this.warningMessage("用户名已存在！")
                    console.log(res);
                }else if(res.data.code === 10200){
                    if(res.data.message == "传入参数格式不合法"){
                        this.warningMessage("信息输入长度不合法或为空！")
                        return;
                    }
                    this.errorMessage("新增失败！")
                }
            }).catch(error => {
                console.log(error);
            })
        },

        deleteAccount(id){
            axios({
                methods:"DELETE",
                url: path + "/account/" + id,
                headers:{
                    id: JSON.parse(localStorage.getItem("account")).id,
                    token: JSON.parse(localStorage.getItem("account")).token,
                }
            }).then((res) => {
              if(res.data.code === 500){
                this.warningMessage("您未有权限!");
              }else if(res.data.code === 20100){
                console.log(res);
                this.list();
              }else{
                this.errorMessage("删除失败!");
              }
            }).catch((error) => {
                console.log(error);
            })
        },
        listAllRole(){
            axios({
                methods:"GET",
                url: path + "/role",
                headers:{
                    id: JSON.parse(localStorage.getItem("account")).id,
                    token: JSON.parse(localStorage.getItem("account")).token,
                }
            }).then(res => {
              if(res.data.code === 500){
                this.warningMessage("您未有权限!");
              }else if(res.data.code === 40100){
                console.log(res.data);
                this.roleOptions = res.data.data
              }else{
                this.errorMessage("遇到未知错误!");
              }
            }).catch(error => {
                console.log(error);
            })
        }
    },
    watch:{
        addVisible(newValue,oldValue){
            if(newValue == false){
                this.accountRole.account.username = "";
                this.accountRole.account.password = "";
                this.accountRole.roleId = "";
            }
        },
        addVisibleTwo(newValue,oldValue){
            if(newValue == false){
                this.accountRole.account.username = "";
                this.accountRole.account.password = "";
                this.accountRole.roleId = "";
            }
        }
    },
    created(){
        this.list();
        this.listAllRole();
   
    },
}
</script>

<style scoped>
.Carousel{
    width: 100%;
    min-height: 100%;
    padding: 15px;
    box-sizing: border-box;
}
.Carousel-Info{
    width: 100%;
    margin-bottom: 15px;
}
.Carousel-list{
    width: 100%;
    margin-bottom: 20px;
}
</style>